Control Statements

Computer Science – XI · Chapter 6 · Questions and Answers

6.1 Control statements – basics

1. What are control statements? Why are they needed?

Control statements are special instructions that alter the normal sequential flow of execution. They let a program decide which statements to execute, when to skip them, and how many times to repeat them. They are needed because real situations require choices and repetition, not just a straight sequence.

2. How are control statements classified?
  • Decision making (selection) statements: execute selectively based on conditions.
  • Iteration (looping) statements: execute a set of instructions repeatedly until a condition is satisfied.
3. What is the flow of control? Which part of the computer evaluates conditions?

The sequence in which statements run is the flow of control. Conditions (comparisons) are processed by the Arithmetic and Logic Unit (ALU), which returns True or False.

4. Which flowchart symbol represents a decision? How many entry and exit points does it have?

The rhombus. It has one entry point and two exit points: one for True/Yes and one for False/No.

6.2 Decision making statements

5. Name the five types of decision making statements in Python.

if, if...else, if...elif...else ladder, match...case, and nested if...else.

6. Explain the if statement with syntax.
if condition:
    block of code

The block runs only when the condition is True; otherwise Python skips the block and continues with the next statement. A colon must follow the condition and the block must be indented.

7. Why is indentation important in Python? What error occurs without it?

Indentation defines the scope of a code block under statements like if. Without proper indentation, Python raises an IndentationError.

8. Write a program to display the score and a congratulatory message if the score is 30 or more (Problem 6.1).
score = int(input("Enter the score: "))
if score >= 30:
    print("Congratulations... You scored above pass mark.")
print("Your score is ", score)

The last line is outside the if block, so the score is always displayed.

9. Explain if...else with syntax. Write the attendance eligibility program (Problem 6.3).
if condition:
    Statement block 1
else:
    Statement block 2

Block 1 runs if the condition is True, otherwise block 2 runs. Only one block executes.

attendance = int(input("Enter your attendance percentage: "))
if attendance >= 75:
    print("You are eligible to attend the exam.")
else:
    print("You have to apply for condonation.")
10. Write a program to display the greater of two heights (Problem 6.4).
h1 = int(input("Enter the height of first student: "))
h2 = int(input("Enter the height of second student: "))
if h1 > h2:
    print("Larger height is: ", h1)
else:
    print("Larger height is: ", h2)
11. Explain if...elif...else. How are conditions checked? Is else compulsory?
if condition1:
    Statement Block 1
elif condition2:
    Statements Block 2
else:
    Block when all conditions are False

Conditions are checked from top to bottom. As soon as one is True, its block runs and the remaining conditions are skipped. If none is True, the else block runs. The else part is optional. Use it to select one action from several.

12. Write a program to check whether a number is positive, negative or zero (Problem 6.5).
n = int(input("Enter a number: "))
if n > 0:
    print(n, "is positive")
elif n < 0:
    print(n, "is negative")
else:
    print(n, "is zero")
13. What is the match–case statement? Give its syntax. Which Python version introduced it?

Introduced in Python 3.10. It compares a value against several patterns and executes the block of the first matching pattern, somewhat like a switch statement in other languages. It is useful when a decision depends on the value of a single variable (menu options, days of week, fixed codes, grades).

match expression:
    case value1:
        Statements Block 1
    case value2:
        Statements Block 2
    case _:
        Default Statements Block

The underscore _ case is the default action when no case matches. Case values can be integers, strings, tuples or other literal patterns.

14. Write a program to display the day of the week using match–case (1 = Sunday … 7 = Saturday) (Problem 6.6).
day = int(input("Enter a number (1-7): "))
match day:
    case 1:
        print("Sunday")
    case 2:
        print("Monday")
    case 3:
        print("Tuesday")
    case 4:
        print("Wednesday")
    case 5:
        print("Thursday")
    case 6:
        print("Friday")
    case 7:
        print("Saturday")
    case _:
        print("Invalid day number")
15. Write a program to print the grade for a score out of 100 (Problem 6.7).

Grades: 90+ A+, 80–89 A, 70–79 B+, 60–69 B, 50–59 C+, 40–49 C, 30–39 D+, 20–29 D, below 20 E. Using match–case with a pattern variable s and if guards:

score = int(input("Enter the score (out of 100): "))
match score:
    case s if 90 <= s <= 100:
        print("Grade: A+")
    case s if 80 <= s <= 89:
        print("Grade: A")
    case s if 70 <= s <= 79:
        print("Grade: B+")
    case s if 60 <= s <= 69:
        print("Grade: B")
    case s if 50 <= s <= 59:
        print("Grade: C+")
    case s if 40 <= s <= 49:
        print("Grade: C")
    case s if 30 <= s <= 39:
        print("Grade: D+")
    case s if 20 <= s <= 29:
        print("Grade: D")
    case s if 0 <= s < 20:
        print("Grade: E")
    case _:
        print("Invalid Score")
16. What is the use of the | symbol in match–case? Why is case 10 or 9: invalid?

| (pipe) is an OR pattern that lets one case match several values:

score = 10
match score:
    case 10 | 9:
        print("Excellent")

It works only inside a case pattern. case 10 or 9: is invalid because or returns a Boolean result, not a pattern.

17. What is nesting? What is a nested if...else? Give both forms.

Writing one decision-making statement inside another is nesting. A nested if...else places an if...else inside the if or the else block of another, so a second-level decision is made only after the first condition is evaluated.

# inner decision inside the if block
if condition1:
    if condition2:
        ...both True
    else:
        ...condition1 True, condition2 False
else:
    ...condition1 False

# inner decision inside the else block
if condition1:
    ...condition1 True
else:
    if condition2:
        ...condition1 False, condition2 True
    else:
        ...both False
18. Write a program to check for a leap year using nested if...else (Problem 6.8). Give test cases.
year = int(input("Enter a year: "))
if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print("Leap year")
        else:
            print("Not a leap year")
    else:
        print("Leap year")
else:
    print("Not a leap year")
YearBy 4?By 100?By 400?Output
2000YesYesYesLeap year
2001No––Not a leap year
2004YesNo–Leap year
2100YesYesNoNot a leap year

Selection – Let us do

19. Check whether a number is even or odd (if...else).

Algorithm: Start → Input N → If N % 2 == 0 print "Even" else print "Odd" → Stop.

n = int(input("Enter a number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
20. Print the largest of three numbers using if...elif...else.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a >= b and a >= c:
    print("Largest is", a)
elif b >= a and b >= c:
    print("Largest is", b)
else:
    print("Largest is", c)
21. Check eligibility for a senior citizen discount (age ≥ 60).
age = int(input("Enter age: "))
if age >= 60:
    print("Eligible for senior citizen discount")
else:
    print("Not eligible for senior citizen discount")
22. Apply 10% discount if the bill is above ₹1000, otherwise 5%; print the final amount.
bill = float(input("Enter the total bill amount: "))
if bill > 1000:
    final = bill - bill * 10 / 100
else:
    final = bill - bill * 5 / 100
print("Final amount =", final)

Example: 1200 → 1080.0; 800 → 760.0.

23. Check whether a year is a century year (divisible by 100).
year = int(input("Enter a year: "))
if year % 100 == 0:
    print("Century year")
else:
    print("Not a century year")
24. Check whether a student passed (marks ≥ 30 → Pass, otherwise Fail).
marks = int(input("Enter marks: "))
if marks >= 30:
    print("Pass")
else:
    print("Fail")
25. Check whether a character is a vowel or consonant using match–case.
ch = input("Enter a character: ").lower()
match ch:
    case 'a' | 'e' | 'i' | 'o' | 'u':
        print("Vowel")
    case _:
        print("Consonant")

The OR pattern | groups the five vowels in one case. (A fuller program could first check that the input is a letter.)

26. Classify monthly electricity consumption: ≤100 Low, 101–300 Moderate, above 300 High.
units = int(input("Enter units consumed: "))
if units <= 100:
    print("Low usage")
elif units <= 300:
    print("Moderate usage")
else:
    print("High usage")
27. Identify and correct the errors in each code.
CodeErrorCorrection
1. Positive/negative/zeroSyntax: missing colon after if n > 0if n > 0:
2. Eligible if age ≥ 18Indentation: print statements are not indented under if and elseIndent both print statements
3. Leap yearLogic: 2100 is divisible by 4, so the first branch prints "Leap year" and the 100/400 checks are never reachedUse if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: or the nested form
4. Pass if mark ≥ 30Logic/syntax: = is assignment, not comparison, and the condition should be ≥if mark >= 30:
28. Predict the output: (1) n = 7 with if n > 10 / elif n > 5 / else; (2) score = 85 with match score // 10 (cases 10|9, 8, 7, _); (3) marks = 72 with the grade ladder.

(1) Greater than 5 (the first condition is False, the second is True).

(2) A (85 // 10 = 8, which matches case 8).

(3) B+ (72 fails ≥ 90 and ≥ 80, but satisfies ≥ 70).

6.3–6.4.1 Iteration and the while loop

29. What is iteration (looping)? Why are loops used?

Iteration is executing a set of statements repeatedly as long as a specified condition remains true; it ends when the condition becomes false. Loops automate repetitive tasks without rewriting instructions, making programs efficient, organised and easy to maintain.

30. What are the four parts of a loop?
  • Initialisation: setting the starting values (e.g. i = 1, total = 0).
  • Condition checking: deciding before each cycle whether to continue (e.g. i <= 6).
  • Body: the statements repeated (e.g. add the mark to the total).
  • Updation: changing the counter so the loop moves toward termination (e.g. i = i + 1).

In Python these parts may not always appear explicitly or in the same place, but conceptually they exist in every loop.

31. Write the algorithm to print numbers 1 to 10 and to find the sum and average of 6 subjects (Problems 6.9 and 6.10).

1 to 10: Start; i = 1; Repeat steps 4 and 5 while i ≤ 10; Print i; i = i + 1; Stop.

Sum and average: Start; i = 1, sum = 0; Repeat steps 4 to 6 while i ≤ 6; Input score; sum = sum + score; i = i + 1; average = sum / 6; Print sum and average; Stop.

In the flowchart, the rhombus tests the condition and a flow line returns from the update step to the rhombus, forming a cycle.

32. Explain the while loop. Why is it called an indefinite loop?
while condition:
    statements

The condition is evaluated before every iteration. While it is True the body executes; when it becomes False, control moves to the statement after the loop. It is called an indefinite loop because it is used when the number of repetitions is not known in advance and depends on a condition. Initialisation and updation are not part of the syntax; the programmer writes them separately.

33. Write a program to count the number of digits in a number (Problem 6.11).
n = int(input("Enter a number: "))
count = 0
while n > 0:
    count = count + 1
    n = n // 10
print("Number of digits:", count)

For 321: n becomes 32, 3, 0 and count becomes 3.

34. Explain the menu-driven calculator program (Problem 6.12).

A while loop repeats as long as choice != 5. Each time it displays the menu (1 Add, 2 Subtract, 3 Multiply, 4 Divide, 5 Exit), reads the choice, and for options 1–4 reads two numbers and prints the result. For division it checks that the divisor is not zero. Choosing 5 prints "Program ended" and the condition becomes False. The number of repetitions depends on the user, so it is an indefinite loop.

choice = 0
while choice != 5:
    print("\nArithmetic Menu")
    print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Exit")
    choice = int(input("Enter your choice: "))
    if choice in (1, 2, 3, 4):
        a = float(input("Enter first number: "))
        b = float(input("Enter second number: "))
        if choice == 1:
            print("Result =", a + b)
        elif choice == 2:
            print("Result =", a - b)
        elif choice == 3:
            print("Result =", a * b)
        elif b != 0:
            print("Result =", a / b)
        else:
            print("Cannot divide by zero")
    elif choice == 5:
        print("Program ended")
    else:
        print("Invalid choice")
35. What is an infinite loop? How can it be avoided?

An infinite loop occurs when the loop's condition never becomes false, often because the updation step is missing or incorrect. It can freeze or slow down the system. Avoid it by designing loops carefully, ensuring correct updation inside the body, and confirming the condition will eventually become false.

while loop – Let us do

36. Print the numbers from 1 to 20; display even numbers between 1 and 50.
i = 1
while i <= 20:
    print(i)
    i = i + 1

i = 2
while i <= 50:
    print(i, end=" ")
    i = i + 2
37. Find the sum of the first 10 natural numbers.
i = 1
total = 0
while i <= 10:
    total = total + i
    i = i + 1
print("Sum =", total)

Output: Sum = 55.

38. Print the multiplication table of a given number.
n = int(input("Enter a number: "))
i = 1
while i <= 10:
    print(n, "x", i, "=", n * i)
    i = i + 1
39. Check whether a number is perfect.

A perfect number equals the sum of its proper divisors (e.g. 6 = 1 + 2 + 3).

n = int(input("Enter a number: "))
i = 1
total = 0
while i < n:
    if n % i == 0:
        total = total + i
    i = i + 1
if total == n and n > 0:
    print(n, "is a perfect number")
else:
    print(n, "is not a perfect number")
40. Reverse the digits of a number; find the sum of digits.
n = int(input("Enter a number: "))
rev = 0
total = 0
while n > 0:
    d = n % 10
    rev = rev * 10 + d
    total = total + d
    n = n // 10
print("Reversed number =", rev)
print("Sum of digits =", total)

For 123: reverse 321, sum of digits 6.

41. Find the factorial of a number.
n = int(input("Enter a number: "))
fact = 1
i = 1
while i <= n:
    fact = fact * i
    i = i + 1
print("Factorial =", fact)

For 5: 120.

42. Check whether a number is a palindrome.
n = int(input("Enter a number: "))
original = n
rev = 0
while n > 0:
    rev = rev * 10 + n % 10
    n = n // 10
if rev == original:
    print("Palindrome")
else:
    print("Not a palindrome")
43. Keep accepting numbers and find their total until the user enters 0.
total = 0
n = int(input("Enter a number (0 to stop): "))
while n != 0:
    total = total + n
    n = int(input("Enter a number (0 to stop): "))
print("Total =", total)
44. Predict the output of the six while loop codes.
CodeOutput
1. i=1; while i<=5: print(i); i=i+11 2 3 4 5 (each on a new line)
2. i=10; while i>=7: print("Hi"); i=i-1Hi printed 4 times (i = 10, 9, 8, 7)
3. i=2; while i<=10: print(i, end=" "); i=i+32 5 8
4. total of 1 to 515
5. i=1; while i<20: if i%4==0: print(i, end=" "); i=i+34 16 (i takes 1, 4, 7, 10, 13, 16, 19)
6. i=5; while i>0: print(i); i=i-2; then print("End")5, 3, 1 on separate lines, then End
45. Identify and correct the errors in the while loop codes.
PurposeErrorCorrection
Print 1 to 5Syntax: missing colon after while i <= 5while i <= 5:
Even numbers 2 to 20Logic: i = i + 1 prints every numberi = i + 2
Reverse a numberLogic: rev is never updated, so it prints 0Add rev = rev * 10 + n % 10 before n = n // 10
FactorialLogic: fact = 0 and it is never multipliedUse fact = 1 and add fact = fact * n inside the loop before n = n - 1

6.4.2 for loop

46. What is a for loop? Why is it a definite loop?

A for loop iterates over a range of values or the elements of a sequence (string, list, tuple), processing each item one by one. It is definite because the number of repetitions is known beforehand.

47. Explain range() with one, two and three parameters.
FormMeaningExample
range(n)0 to n–1range(5) → 0 1 2 3 4
range(start, stop)start up to, but excluding, stoprange(1, 11) → 1 to 10
range(start, stop, step)moves by step each time; negative step counts downrange(2, 21, 2) → 2, 4, …, 20

The stop value is always excluded. If start > stop with a positive step, the sequence is empty and the loop does not run; use a negative step to count down.

48. Write programs to print 0 to 4, 1 to 10, and even numbers from 2 to 20 using for.
for i in range(5):
    print(i)

for roll in range(1, 11):
    print("Number:", roll)

for num in range(2, 21, 2):
    print(num)
49. Write a for program for the sum and average of scores of 6 subjects.
sum = 0
for i in range(1, 7):
    score = float(input("Enter score of subject " + str(i) + ": "))
    sum = sum + score
average = sum / 6
print("Total Score:", sum)
print("Average Score:", average)

range(1, 7) gives 1 to 6 and initialises the loop variable; sum is initialised to 0 before the loop.

50. How does a for loop work with strings? Print a string with a space after each character (Problem 6.15).

The loop variable takes one character of the string in each iteration.

text = input("Enter a string: ")
for ch in text:
    print(ch, end=" ")

Input "Python is interesting" prints P y t h o n i s .... end=" " keeps the output on one line.

51. What is the purpose of the underscore in for _ in range(5)?

The underscore is a placeholder used when the loop variable is not needed; its value is intentionally ignored. The code for _ in range(5): print("Hello") prints Hello five times.

52. Differentiate between for and while loops.
Aspectfor loopwhile loop
NatureDefinite; number of repetitions knownIndefinite; depends on a condition
ControlIterates over a sequence (range, list, tuple, string)Repeats as long as the condition is true
Initialisation and updationUsually automatic (e.g. by range())Written manually before and inside the loop
Condition checkingImplicit, from the sequenceExplicit, before every iteration
UseFixed counts, sequences, tablesInput-driven or condition-driven loops

for loop – Let us do

53. Display the first 15 natural numbers; print squares and cubes of 1 to 10.
for i in range(1, 16):
    print(i, end=" ")

for i in range(1, 11):
    print(i, "square =", i * i, " cube =", i ** 3)
54. Display the sum of even numbers from 2 to 20.
total = 0
for i in range(2, 21, 2):
    total = total + i
print("Sum =", total)

Output: Sum = 110.

55. Count how many numbers between 1 and 50 are divisible by 3 or 5.
count = 0
for i in range(1, 51):
    if i % 3 == 0 or i % 5 == 0:
        count = count + 1
print("Count =", count)

Output: 23 (16 multiples of 3 + 10 multiples of 5 – 3 multiples of 15).

56. Find the product of all numbers in a list entered by the user.
nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
product = 1
for x in nums:
    product = product * x
print("Product =", product)
57. Display all numbers between 100 and 200 that are multiples of 7.
for i in range(100, 201):
    if i % 7 == 0:
        print(i, end=" ")

Output: 105, 112, 119, …, 196. A shortcut is range(105, 201, 7).

58. Find the factorial of a number using a for loop.
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
    fact = fact * i
print("Factorial =", fact)
59. Find the largest number in a list; count numbers greater than a given number.
nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
largest = nums[0]
for x in nums:
    if x > largest:
        largest = x
print("Largest =", largest)

k = int(input("Enter a number to compare: "))
count = 0
for x in nums:
    if x > k:
        count = count + 1
print("Numbers greater than", k, ":", count)
60. Identify and correct the errors in the for loop codes.
PurposeErrorCorrection
Print 1 to 5Syntax: missing colon; also range(1, 5) stops at 4for i in range(1, 6):
Even numbers 2 to 10As printed, this code is correct and gives 2, 4, 6, 8, 10No change needed
Print 1 to 10Logic: i = i + 1 is unnecessary; the loop variable is reset by range() on every iterationRemove that line
Print 10 to 1Logic: range(10, 1) is empty because the step is positiverange(10, 0, -1)
61. Predict the output: (1) for i in range(5) (2) for i in range(1, 6): print(i, end=" ") (3) for i in range(10, 5, -2).

(1) 0 1 2 3 4, each on a new line.

(2) 1 2 3 4 5 on one line.

(3) 10, 8, 6, each on a new line.

6.5 Loop control statements

62. Name the four loop control keywords and their purposes.
KeywordPurposeEffect
breakTerminates the loop immediatelyExits the loop entirely
continueSkips the rest of the current iterationProceeds to the next iteration
passDoes nothing (placeholder)Loop continues normally
elseRuns after the loop completes normallySkipped if the loop ends with break
63. Explain break with a for and a while program that stop at roll number 5 (Problems 6.16 and 6.17).

break ends the loop at once and control passes to the first statement after the loop.

for roll in range(1, 11):
    print("Roll Number:", roll)
    if roll == 5:
        print("Stopping attendance check.")
        break

roll = 1
while roll <= 10:
    print("Roll Number:", roll)
    if roll == 5:
        print("Stopping attendance check.")
        break
    roll = roll + 1

Both print roll numbers 1 to 5 and then the message.

64. Explain continue by printing roll numbers 1 to 10 except 5 (Problem 6.18).
for roll in range(1, 11):
    if roll == 5:
        continue
    print("Roll Number:", roll)

When roll is 5, continue skips the print() and moves to the next number. The loop is not terminated.

65. What is the pass statement? How does it differ from continue? (Problem 6.19)

pass is a null statement that does nothing. It is used where a statement is syntactically required but no action is needed, e.g. to keep the structure of a block during development. Unlike continue, it does not skip the remaining statements of the iteration.

count = 0
for i in range(1, 6):
    subject = input("Enter subject name " + str(i) + ": ")
    if subject == "":
        pass              # nothing to do for empty input
    else:
        count = count + 1
    print("Number of iterations completed:", i)
print("Number of subjects entered:", count)
66. Explain the else clause with loops. Write a program to check whether a number is prime (Problem 6.20).

The else block of a for or while loop runs only if the loop finishes all its iterations without a break.

n = int(input("Enter a number: "))
for i in range(2, n):
    if n % i == 0:
        print("Not a prime number")
        break
else:
    print("Prime number")

If a divisor is found, break skips the else. If none is found, the loop completes and "Prime number" is printed. For 49 → Not a prime; for 59 → Prime. (For n = 0 or 1 the loop does not run, so this version would report prime; add a check n > 1 for complete correctness.)

67. Keep reading numbers and stop when the user enters a negative number; print 1 to 100 but stop at 42.
n = int(input("Enter a number: "))
while n >= 0:
    print("You entered", n)
    n = int(input("Enter a number: "))
print("Negative number entered. Stopped.")

# or using break
while True:
    n = int(input("Enter a number: "))
    if n < 0:
        break

for i in range(1, 101):
    print(i, end=" ")
    if i == 42:
        break
68. Print 1 to 30 skipping numbers divisible by 3; print roll numbers 1 to 20 excluding absentees.
for i in range(1, 31):
    if i % 3 == 0:
        continue
    print(i, end=" ")

absent = list(map(int, input("Enter absent roll numbers: ").split()))
for roll in range(1, 21):
    if roll in absent:
        continue
    print(roll, end=" ")
69. Accept marks until 999 is entered (break); ignore marks above 100 (continue); display the valid marks.
valid = []
while True:
    mark = int(input("Enter mark (999 to stop): "))
    if mark == 999:
        break
    if mark > 100:
        print("Invalid mark ignored")
        continue
    valid.append(mark)
print("Valid marks entered:", valid)
70. PIN verification: 5 attempts, "Access Granted" with break, "Account Locked" with else.
correct_pin = 4321
for attempt in range(5):
    pin = int(input("Enter 4-digit PIN: "))
    if pin == correct_pin:
        print("Access Granted")
        break
else:
    print("Account Locked")

The else runs only if all five attempts fail (no break).

71. Identify and correct the errors in the loop control codes.
PurposeErrorCorrection
Numbers 1 to 10, stop at 5Syntax: if i = 5 uses assignmentif i == 5:
Odd numbers 1 to 10Syntax: if i % 2 = 0 uses assignmentif i % 2 == 0:
Print 1 to 5Logic: pass at i == 3 and printing in else skips 3, so output is 1 2 4 5Remove the if/else and just print(i)
72. Predict the output of the nine loop control codes.
No.Output
1. while with pass at i == 31 2 3 4 5 (each on a new line)
2. break at i == 51 2 3 4 (each on a new line)
3. continue at i == 4 (i incremented first)1 2 3 5 6 (each on a new line)
4. skip even numbers1 3 5 7
5. break at i == 71 2 3 4 5 6
6. pass when i > 3, then print1 2 3 4 5 (each on a new line)
7. while with break at i == 4 and else "Done"1 2 3 (else skipped because of break, so no "Done")
8. for: continue at 3, break at 6, else "Finished"1 2 4 5 (each on a new line; no "Finished" because of break)
9. skip even i with continue, else "End"1, 3, 5, then End

6.6 Nested loops

73. What is a nested loop? What are the outer and inner loops?

A nested loop is a loop written inside another loop. The containing loop is the outer loop and the one inside is the inner loop. For every single iteration of the outer loop, the inner loop completes all its iterations. Nested loops handle two-level repetition such as tables, patterns, and rows and columns.

74. Give the general form of a nested for and a nested while.
for variable1 in sequence1:        # Outer loop
    for variable2 in sequence2:    # Inner loop
        statements

while condition1:                  # Outer loop
    while condition2:              # Inner loop
        statements

Any combination (while inside for, for inside while) is allowed.

75. Write a program to read marks of 6 subjects for 5 students and display each student's total (Problem 6.21).
for roll in range(1, 6):
    print("\nEntering marks of Student", roll)
    total = 0
    for subject in range(1, 7):
        mark = float(input("Enter mark for Subject " + str(subject) + ": "))
        total += mark
    print("Total marks for Student", roll, ":", total)

total is reset to 0 for each student; the inner loop runs 6 times per student.

76. Display a 5 × 5 multiplication table (Problem 6.22).
for i in range(1, 6):
    for j in range(1, 6):
        print(i, '*', j, '=', i * j)
    print()
77. Print a right-angled triangle using nested while (Problem 6.23).
i = 1
while i <= 5:
    j = 1
    while j <= i:
        print("*", end=" ")
        j = j + 1
    print()
    i = i + 1

The inner print("*", end=" ") keeps the row on one line; the outer print() moves to the next line. Printing j instead of "*" gives the number triangle 1 / 1 2 / 1 2 3 …

78. How do break and continue behave in nested loops?

They affect only the loop in which they appear. A break in the inner loop stops only the inner loop and control passes to the next statement of the outer loop. A continue in the inner loop skips the rest of that inner iteration and moves to the inner loop's next cycle.

79. Print the four right-angled triangle patterns for a number of lines entered by the user.
n = int(input("Enter number of lines: "))

# Pattern 1: 1 / 1 2 / 1 2 3 ...
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

# Pattern 2: 1 2 3 4 5 / 1 2 3 4 / ... / 1
for i in range(n, 0, -1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

# Pattern 3: * * * * * / * * * * / ... / *
for i in range(n, 0, -1):
    for j in range(i):
        print("*", end=" ")
    print()

# Pattern 4: right-aligned 1 / 1 2 / 1 2 3 ...
for i in range(1, n + 1):
    print("  " * (n - i), end="")
    for j in range(1, i + 1):
        print(j, end=" ")
    print()
80. Use a nested while loop to print the multiplication tables from 1 to 10.
i = 1
while i <= 10:
    j = 1
    while j <= 10:
        print(i, "x", j, "=", i * j)
        j = j + 1
    print()
    i = i + 1
81. Input marks of 3 students in 4 subjects and print each student's total.
for student in range(1, 4):
    total = 0
    for subject in range(1, 5):
        mark = float(input("Student " + str(student) + ", subject " + str(subject) + ": "))
        total = total + mark
    print("Total marks of student", student, "=", total)
82. Print all ordered pairs (i, j) with i and j from 1 to 4 using nested while.
i = 1
while i <= 4:
    j = 1
    while j <= 4:
        print("(", i, ",", j, ")", end=" ")
        j = j + 1
    print()
    i = i + 1

This prints 16 pairs, from (1, 1) to (4, 4).